package com.qianf.foodsending.controller;


import com.qianf.foodsending.entity.ResponseData;
import com.qianf.foodsending.entity.UserInfo;
import com.qianf.foodsending.service.UserLoginService;
import com.qianf.foodsending.utils.KeyUtil;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;



@RequestMapping("/user")
@RestController
public class UserLoginController {

    @Autowired
    private UserLoginService userLoginService;

    @RequestMapping("/login")
    public ResponseData loginUser (String name, String password) {

        UserInfo userInfo = userLoginService.loginUser(name);

        ResponseData<Object> responseData = new ResponseData();

        if (userInfo == null) {

            responseData.setCode(1);

            responseData.setMsg("用户名或密码不正确");

            return responseData;

        }

        if (!userInfo.getPassword().equals(password)) {

            responseData.setCode(1);

            responseData.setMsg("用户名或密码不正确");

            return responseData;

        } else {

            responseData.setCode(0);
            responseData.setMsg("登录成功");
            responseData.setData(userInfo);
            return responseData;
        }

    }

//    @Test
//    public void Test (HttpSession httpSession) {
//
//        String openid = (String) httpSession.getAttribute("openid");
//
//
//
//    }


    /**
     * 注册用户
     * @param name
     * @param password
     * @param password2
     * @return
     */
    @RequestMapping("/register")
    public ResponseData registerUser (String name,String password,String password2) {

        ResponseData<Object> responseData = new ResponseData();

        UserInfo userInfo1 = userLoginService.loginUser(name);

        if (userInfo1 != null){
            responseData.setCode(1);
            responseData.setMsg("注册失败，用户已存在！");
            return responseData;

        }

        if (!password.equals(password2)){
            responseData.setCode(1);
            responseData.setMsg("注册失败，两次密码输入不一致！");
            return responseData;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setName(name);
        userInfo.setPassword(password);

        String uniqueKey = KeyUtil.genUniqueKey();

        StringBuffer stringBuffer = new StringBuffer("openid_" + uniqueKey);

        userInfo.setOpenid(String.valueOf(stringBuffer));

        int i = userLoginService.registerUser(userInfo);

        if (i > 0) {
            responseData.setCode(0);
            responseData.setMsg("注册成功");

            return responseData;

        } else {
            responseData.setMsg("注册失败");
            responseData.setCode(1);
            return responseData;
        }


    }


}
